import os from 'os'
import path from 'path'
import electron, {app, BrowserWindow} from 'electron'
import './store';
import lyric from "./lyric";
// @ts-ignore
app.lyric = lyric;

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
require('@electron/remote/main').initialize();
// https://stackoverflow.com/questions/42524606/how-to-get-windows-version-using-node-js
const isWin7 = os.release().startsWith('6.1')
if (isWin7) app.disableHardwareAcceleration()

if (!app.requestSingleInstanceLock()) {
    app.quit()
    process.exit(0)
}

let win: BrowserWindow | null = null

async function loadExtensions() {
    const extensionsDir = path.join(__dirname, '../../extensions');
    const fs = require('fs');
    fs.readdirSync(extensionsDir).forEach((dir: string) => {
        dir = path.join(extensionsDir, dir);
        if (fs.statSync(dir).isDirectory()) {
            electron.session.defaultSession.loadExtension(dir);
        }
    });
}

async function createWindow() {
    win = new BrowserWindow({
        height: 600,
        width: 800,
        minHeight: 600,
        minWidth: 800,
        webPreferences: {
            preload: path.join(__dirname, '../preload/index.cjs'),
            webSecurity: false
        },
    })

    require("@electron/remote/main").enable(win.webContents);

    if (app.isPackaged) {
        win.loadFile(path.join(__dirname, '../renderer/index.html'))
    } else {
        const pkg = await import('../../package.json')
        const url = `http://${pkg.env.HOST || '127.0.0.1'}:${pkg.env.PORT}`
        win.loadURL(url)
        loadExtensions()
        win.webContents.openDevTools();
    }
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
    win = null
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('second-instance', () => {
    if (win) {
        // someone tried to run a second instance, we should focus our window.
        if (win.isMinimized()) win.restore()
        win.focus()
    }
})

app.on('activate', () => {
    const allWindows = BrowserWindow.getAllWindows()
    if (allWindows.length) {
        allWindows[0].focus()
    } else {
        createWindow()
    }
})

// @TODO
// auto update
/* if (app.isPackaged) {
  app.whenReady()
    .then(() => import('electron-updater'))
    .then(({ autoUpdater }) => autoUpdater.checkForUpdatesAndNotify())
    .catch((e) =>
      // maybe you need to record some log files.
      console.error('Failed check update:', e)
    )
} */
